package com.wangyb.wework.wxApi.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.annotation.JSONField;
import com.wangyb.wework.enums.WxCallbackEventEnum;
import com.wangyb.wework.utils.crypt.MessageUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Map;

/**
 * @Author: wangyb
 * @Date: 2021/8/5 3:26 下午
 */
@Data
@Slf4j
public class WxCallbackMsg {
	@JSONField(name = "tousername")
	private String wxCorpId;
	private Long corpId;
	@JSONField(name = "fromusername")
	private String fromUserName;
	@JSONField(name = "createtime",format="unixtime")
	private Date createTime;
	@JSONField(name = "msgtype")
	private String msgType;
	@JSONField(name = "event")
	private WxCallbackEventEnum event;
	@JSONField(name = "changetype")
	private String changType;

	private Map<String,Object> originMap;
	private String origin;


	/**
	 * 通过消息参数名获取值，不区分大小写
	 * @param key
	 * @return
	 */
	public String getString(@NotNull String key){
		return String.valueOf(this.originMap.get(key.toLowerCase()));
	}
	public Integer getInteger(@NotNull String key){
		return Integer.valueOf(getString(key));
	}

	public static WxCallbackMsg parse(String msg){
		WxCallbackMsg callbackMsg = null;
		//将post数据转换为map
		Map<String, Object> dataMap = MessageUtil.parseXml(msg);
		Object xmlBody = dataMap.get("xml");
		JSONObject data = JSONObject.parseObject(JSON.toJSONString(xmlBody));
		callbackMsg = JSONObject.toJavaObject(data, WxCallbackMsg.class);
		callbackMsg.setOrigin(msg);
		if (xmlBody instanceof Map){
			callbackMsg.setOriginMap((Map)xmlBody);
		}
		try{
			WxCallbackEventEnum event = WxCallbackEventEnum.get(data.getString("event"));
			callbackMsg.setEvent(event);
		}catch (IllegalArgumentException e){
			log.debug(e.getMessage());
		}
		return callbackMsg;
	}

	/**
	 * 获取redis PUBSUB topic name
	 * @return
	 */
	public String getTopicName(){
		return formatTopicName(this.event,this.changType);
	}

	/**
	 * 根据参数创建 redis PUBSUB topic name
	 * @param event
	 * @param changType
	 * @return
	 */
	public final static String getTopicName(WxCallbackEventEnum event, String changType){
		return formatTopicName(event,changType);
	}
	private static String formatTopicName(WxCallbackEventEnum event, String changType){
		return String.format("%s:%s",event.name(),changType);
	}

}
